package com.hdax.dm.listener;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hdax.dm.entity.order.OrderTxMsg;
import com.hdax.dm.entity.scheduler.DmSchedulerSeat;
import com.hdax.dm.entity.scheduler.SchedulerTxMsg;
import com.hdax.dm.service.SchedulerSeatService;
import com.hdax.dm.service.TxMsgService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RabbitListener(queues = {"dm_order_tx"})
@Component
public class SeatTxListener {

    @Autowired
    private TxMsgService txMsgService;
    @Autowired
    private SchedulerSeatService seatService;

    @RabbitHandler
    @Transactional
    public void seatCommit(@Payload OrderTxMsg txMsg, Channel channel, Message message) throws Exception{
        String msg = txMsg.getMsg();
        SchedulerTxMsg txMsg1 = new SchedulerTxMsg();
        BeanUtils.copyProperties(txMsg,txMsg1);
        Map<String,Object> map = JSONUtil.toBean(msg,Map.class);
        String[] seatPositions = ((JSONArray) map.get("seatPositions")).toArray(new String[0]);
        List<DmSchedulerSeat> seats = new ArrayList<>();
        for (String seatPosition : seatPositions) {
            long x = Long.parseLong(seatPosition.split("_")[0]);
            long y = Long.parseLong(seatPosition.split("_")[1]);
            DmSchedulerSeat seat = seatService.getOne(new QueryWrapper<DmSchedulerSeat>()
                    .eq("scheduleId",map.get("scheduleId"))
                    .eq("x",x)
                    .eq("y",y)
            );
            seat.setOrderNo((String) map.get("orderNo"));
            seat.setUserId(Long.valueOf(map.get("userId").toString()));
            seat.setStatus(2L);
            seats.add(seat);//要批量修改的座位
        }
        seatService.updateBatchById(seats);
        txMsgService.save(txMsg1);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        txMsgService.update(new UpdateWrapper<SchedulerTxMsg>()
                .set("version",txMsg1.getVersion()+1)
                .set("atime", LocalDateTime.now())
                .set("msg_result",1)
                .eq("id",(String) map.get("orderNo"))
                .eq("version",txMsg1.getVersion())
        );
    }
}
